import React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
// 引入二级路由
import Admin from '@/router/Admin';
// 引入样式
import '@/assets/css/dashboard.css'

import {
	MenuFoldOutlined,
	MenuUnfoldOutlined,
	AppstoreOutlined,
	PieChartOutlined,
	ExclamationCircleOutlined,
} from '@ant-design/icons';

import { Layout, Menu, theme, Button, Modal, message } from 'antd';
import { Link, useHistory, useLocation } from 'react-router-dom';

import { getadmininfo, jwtPreCheckFn } from '@/api/dashboard';

const { Header, Sider, Content } = Layout;

const Dashboard = () => {
	// 控制左侧菜单折叠的变量
	const [collapsed, setCollapsed] = useState(false);
	const {
		token: { colorBgContainer },
	} = theme.useToken();

	// 获取redux仓库中的store保存的菜单数据acl
	const { acl } = useSelector((state) => state)
	// console.log(acl);


	//左侧menu 菜单的函数
	function getItem(label, key, icon, children, type) {
		return {
			key,
			icon,
			children,
			label,
			type,
		};
	}

	const items = [];
	acl.map((v, i) => {
		if (v.children.length !== 0) {
			// 说明 该菜单有二级菜单
			items.push(getItem(v.auth_name, v.auth_path, <AppstoreOutlined />, v.children.map((v1, i1) => {
				// 只渲染v1.is_nav 为1的菜单项
				if (v1.is_nav === 1) {
					return getItem(<Link to={v1.auth_path}>{v1.auth_name}</Link>, v1.auth_path)
				}
			})))
		} else {
			items.push(getItem(<Link to={v.auth_path}>{v.auth_name}</Link>, v.auth_path, <PieChartOutlined />))
		}
	})

	// console.log('items', items);
	const [accountInfo, setAccountInfo] = useState({})
	const [islogin, setIslogin] = useState(false)
	useEffect(() => {
		// 获取用户信息
		getadmininfo().then((res) => {
			// console.log('000',res);
			if (res.data.errNo === 0) {
				setAccountInfo(res.data.accountInfo)
			}
		})
		// 验证token信息，查看是否登录接口，防跳墙功能
		jwtPreCheckFn().then((res) => {
			// console.log('che', res);
			if (res.data.errNo !== 0) {
				// 没有登陆
				message.error('请先登录', 1, () => {
					his.push('/login')
				})
			} else {
				setIslogin(true)
			}
		})


	}, [])


	const dispatch = useDispatch()
	const his = useHistory()
	// 定义退出函数
	const loginOut = () => {
		// 没有接口调用，清除登录时的token，user等信息
		// 01：清除 jwt
		// localStorage.removeItem('jwt')

		// dispatch({type:'updateAcl',payload:[]});
		// localStorage.removeItem('persist:userAcl')

		// his.push('/login')

		Modal.confirm({
			title: '提示',
			icon: <ExclamationCircleOutlined />,
			content: '确认要退出码？',
			okText: '确认',
			cancelText: '取消',
			onCancel: () => {
				console.log('点击取消');
			},
			onOk: () => {
				console.log('点击确定');
				localStorage.removeItem('jwt')

				dispatch({ type: 'updateAcl', payload: [] });
				localStorage.removeItem('persist:userAcl')
				// 返回登陆页
				setTimeout(() => {
					his.push('/login')
				}, 1500)
			}
		});

	}

	// 设置默认的选中的菜单项 defaultSelectedKey,
	const loc = useLocation();
	// console.log('loc', loc);
	return (
		<>
			{
				islogin ? <Layout>
					<Sider trigger={null} collapsible collapsed={collapsed}>
						<div className="logo"></div>
						<Menu
							theme="dark"
							mode="inline"
							defaultSelectedKeys={[loc.pathname]}
							// 设置默认打开的是哪个一级菜单
							defaultOpenKeys={[loc.pathname.substring(0, loc.pathname.lastIndexOf('/'))]}
							items={items}
						/>
					</Sider>
					<Layout className="site-layout">
						<Header
							style={{
								padding: 0,
								background: colorBgContainer,
								display: 'flex',
                                alignItems: 'center',
							}}
						>
							{React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
								className: 'trigger',
								onClick: () => setCollapsed(!collapsed),
							})}
							<div style={{
								flex: 1,
								display: 'flex',
								justifyContent: 'space-between',
								alignItems: 'center',
								paddingLeft: '10px',
								paddingRight: '10px'
							}}>
								{/* 显示用户名和角色 */}
								<span>您好，{accountInfo.username}/{accountInfo.role}</span>
								{/* 注销登录按钮 */}
								<Button onClick={() => { loginOut() }}>注销登录</Button>
							</div>
						</Header>
						<Content
							style={{
								margin: '24px 16px',
								padding: 24,
								minHeight: 280,
								background: colorBgContainer,
							}}
						>
							{/* 二级路由 */}
							<Admin></Admin>
						</Content>
					</Layout>
				</Layout> : <></>
			}

		</>
	);
}

export default Dashboard;